package com.example.demo.rabbitMQ;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author suliwei
 * @description:
 * @date 2025/3/4 15:09
 */
@Component
@Slf4j
public class Consumer {

    /**
     * 消费者1 模拟正常处理消息的情况，消息处理完毕发送确认应答
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitListener(queues = "test")
    public void process1(Message message, Channel channel) throws IOException {
        log.info("消费者1 接收消息: " + new String(message.getBody()));
        log.info("消费者1 确认应答消息：" + new String(message.getBody()));
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
    }

    /**
     * 消费者2 模拟处理消息出错的情况，消费者2向rabbitmq发送拒绝应答。
     * 处理失败的消息会被重新放入ready中，再次发送给消费者，直至收到确认应答
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitListener(queues = "test")
    public void process2(Message message, Channel channel) throws IOException {
        log.info("消费者2 接收消息：" + new String(message.getBody()));
        log.info("消费者2 拒绝应答消息：" + new String(message.getBody()));
        channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
    }
}